package net.itemzone.framework.webservice.cxf.server;

import javax.xml.soap.Node;
import javax.xml.soap.SOAPException;
import javax.xml.soap.SOAPHeader;
import javax.xml.soap.SOAPMessage;

import net.itemzone.framework.webservice.cxf.SoapAuthenticationConstants;

import org.apache.cxf.binding.soap.SoapMessage;
import org.apache.cxf.binding.soap.saaj.SAAJInInterceptor;
import org.apache.cxf.interceptor.Fault;
import org.apache.cxf.message.Message;
import org.apache.cxf.phase.AbstractPhaseInterceptor;
import org.apache.cxf.phase.Phase;

/** 
 * <p>Title: </p> 
 * <p>Description: </p>
 * <p>Company: 深圳任子行网络技术有限公司</p> 
 * @version 1.00 May 31, 2009
 * @author ZhaoJunFei
 *  
 * Modified History: 
 *  
 */
public class SoapAuthenticationInterceptor  extends AbstractPhaseInterceptor<Message>{
	private SoapAuthenticationHandler soapAuthenticationHandler;
	
	private SAAJInInterceptor saajIn = new SAAJInInterceptor(); 
	public SoapAuthenticationInterceptor() {
		super(Phase.PRE_PROTOCOL);
	}
	public SoapAuthenticationInterceptor(String phase) {
		super(phase);
	}

	public void handleMessage(Message msg) throws Fault {
		SoapMessage message = (SoapMessage) msg;
		SOAPMessage doc = message.getContent(SOAPMessage.class);
		if (doc == null) {
			saajIn.handleMessage(message);
			doc = message.getContent(SOAPMessage.class);
		}
		SOAPHeader header = null;
		try {
			header = doc.getSOAPHeader();
		} catch (SOAPException e) {
			throw new RuntimeException("SoapAuthenticationInterceptor->分析SOAPHeader错误"+e.getMessage());
		}
		if (header == null) {
			return;
		}
		String namespace = selectSingleNode(header,
				SoapAuthenticationConstants.USERNAME).getNamespaceURI();
		String userName = selectSingleNode(header,
				SoapAuthenticationConstants.USERNAME).getTextContent();
		String password = selectSingleNode(header,
				SoapAuthenticationConstants.PASSWORD).getTextContent();
		soapAuthenticationHandler.authenticate(namespace, userName, password);
		
	}
	public Node selectSingleNode(SOAPHeader header,String queryString ){
		return (Node) header.getElementsByTagName(queryString ).item(0);
	}
	
	public void setSoapAuthenticationHandler(
			SoapAuthenticationHandler soapAuthenticationHandler) {
		this.soapAuthenticationHandler = soapAuthenticationHandler;
	}
}
